package guoanmaker.operator.business.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.dao.LuckdrawRecordAndCouponsDao;
import guoanmaker.operator.business.dao.OperatorActiveTaskDao;
import guoanmaker.operator.business.model.OperatorActiveChance;
import guoanmaker.operator.business.model.OperatorActiveTask;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.OperatorLuckdraw;
import guoanmaker.operator.business.model.OperatorLuckdrawRecord;
import guoanmaker.operator.business.model.PersonalAddress;
import guoanmaker.operator.business.model.ProvideOrderForm;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.LuckdrawRecordAndCoupons;
import guoanmaker.operator.business.modelnobind.OperatorActiveTaskVO;
import guoanmaker.operator.business.modelnobind.OperatorEventDetailsOptions;
import guoanmaker.operator.business.modelnobind.OperatorLuckdrawAndDetails;
import guoanmaker.operator.business.modelnobind.OperatorLuckdrawRecordVO;
import guoanmaker.operator.business.repository.KeyValueRepository;
import guoanmaker.operator.business.repository.OperatorActiveChanceRepository;
import guoanmaker.operator.business.repository.OperatorActiveTaskRepository;
import guoanmaker.operator.business.repository.OperatorActiveTaskTypeRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.OperatorLotteryUrlRepository;
import guoanmaker.operator.business.repository.OperatorLuckdrawRecordRepository;
import guoanmaker.operator.business.repository.PersonalAddressRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideOrderFormRepository;

/**
 * 
 * @author ws
 * @date 2017-11-23
 */
@Service
public class OperatorActiveTaskService implements OperatorActiveTaskServiceInterface {
	@PersistenceContext
	private EntityManager manager;

	@Resource
	private OperatorActiveTaskDao operatorActiveTaskDao;
	
	@Resource
	private KeyValueRepository keyValueRepository;
	
	@Resource
	private OperatorActiveTaskRepository operatorActiveTaskRepository;
	
	@Resource
	private OperatorActiveTaskTypeRepository operatorActiveTaskTypeRepository;
	
	@Resource
	private OperatorEventDetailsRepository operatorEventDetailsRepository; 
	
	@Resource
	private OperatorActiveChanceRepository operatorActiveChanceRepository;
	
	@Resource
	private ProvideOrderFormRepository provideOrderFormRepository;
	
	@Resource
	private OperatorSendMesToCusServiceIntegerface operatorSendMesToCusService;
	
	@Resource
	private OperatorLotteryUrlRepository operatorLotteryUrlRepository;
	
	@Resource
	private OperatorOrderService operatorOrderService;
	
	@Resource
	private OperatorLuckdrawRecordRepository operatorLuckdrawRecordRepository;
	
	@Resource
	private PersonalUserRepository personalUserRepository;
	
	@Resource
	private PersonalAddressRepository personalAddressRepository;
	
	@Resource
	private LuckdrawRecordAndCouponsDao luckdrawRecordAndCouponsdao;
	/**
	 * @description: 从表t_operator_event_details中根据luck_name and activity_type_id  and availability查询记录
	 * @param availability
	 * @param activityTypeId
	 * @param luckName
	 * @return id, eventTitle两个字段
	 */
	public List<OperatorEventDetailsOptions> findOperatorEventDetailsByAvailabilityAndActivityTypeIdAndLuckName(String availability, String activityTypeId, String luckName) {
		
		availability = availability.trim();
		activityTypeId = activityTypeId.trim(); 
		luckName = luckName.trim();
	
		return operatorActiveTaskDao.findOperatorEventDetailsByAvailabilityAndActivityTypeIdAndLuckName(availability, activityTypeId, luckName);
		
	}

	/**
	 * @description:新增或修改任务记录
	 * @param taskId 任务id
	 * @param taskName 任务名称
	 * @param taskTypeId 任务类型id
	 * @param taskAmount 订单金额
	 * @param activeId 活动id
	 * @return ReturnResult
	 */
	@Override
	@Transactional
	public ReturnResult saveOrUpdateOperatorActiveTask(String taskId, String taskName, String taskTypeId, String taskAmount, String activeId) {
		ReturnResult returnResult = new ReturnResult();
		
		if(taskName == null || taskName.trim().length() == 0){
			returnResult.setKey("error");
			returnResult.setValue("任务名称为空");
			return returnResult;
		}
		taskName = taskName.trim();
		//同一任务类型下，任务名称不能重复
		if(operatorActiveTaskDao.countSameTaskName(taskId, taskName, taskTypeId) > 0){
			returnResult.setKey("error");
			returnResult.setValue("已存在相同任务名");
			return returnResult;
		}
		
		
		if(taskAmount == null || taskAmount.trim().length() == 0){
			returnResult.setKey("error");
			returnResult.setValue("订单金额为空");
			return returnResult;
		}
		taskAmount = taskAmount.trim();
		//同一任务类型下，订单金额不能重复
		if(operatorActiveTaskDao.countSameTaskAmount(taskId, taskAmount, taskTypeId) > 0){
			returnResult.setKey("error");
			returnResult.setValue("已存在相同的订单金额");
			return returnResult;
		}
		
		//若任务id存在,则修改表中数据;否则新增表数据
		OperatorActiveTask task = null;
		if(taskId != null && taskId.trim().length() >0){
			task = operatorActiveTaskRepository.findOne(taskId);
		} else{
			task = new OperatorActiveTask();
		}
		task.setActiveTaskName(taskName);
		task.setActiveTaskType(operatorActiveTaskTypeRepository.findOne(taskTypeId));
		task.setActiveTaskAmount(taskAmount);
		task.setDateTime(new Date());
		task.setActive(operatorEventDetailsRepository.findOne(activeId));
		operatorActiveTaskRepository.save(task);
		returnResult.setKey("success");
		returnResult.setValue("操作成功");
		
		return returnResult;
	}

	/**
	 * @description:根据任务id删除任务记录
	 * @param taskId 任务id
	 * @return void
	 */
	@Override
	@Transactional
	public void deleteOperatorActiveTaskById(String taskId) {
		operatorActiveTaskRepository.deleteById(taskId.trim());
	}
	
	/**
	 * @descrption:根据活动名称和活动类型分页查询
	 * @param taskName 任务名称
	 * @param taskTypeId 任务类型id
	 * @param page 当前页
	 * @param size 当前页显示记录的数量
	 * @return
	 */
	@Override
	public Map<String, Object> findByTaskNameAndTaskType(String taskName, String taskTypeId, String page,String size) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		long total = operatorActiveTaskDao.totalByTaskNameAndTaskType(taskName, taskTypeId);
		List<OperatorActiveTaskVO> resultList = operatorActiveTaskDao.findByTaskNameAndTaskType(taskName, taskTypeId, page, size);
		resultMap.put("total", total);
		resultMap.put("list", resultList);
		return resultMap;
	}

	/**
	 * @description:根据订单中的实付金额-优惠金额查询和任务类型id对应的活动url,并添加或修改t_operator_active_chance
	 * @param provideOrderFormId 订单id
	 * @param taskTypeId 任务类型id
	 * @return String url地址
	 */
	@Override
	@Transactional
	public String findActiveURLByTruePriceAndTaskTypeId(String provideOrderFormId, String taskTypeId) {
		//根据订单id获得userId
		ProvideOrderForm provideOrderForm = provideOrderFormRepository.findOne(provideOrderFormId);
		String userId = provideOrderForm.getUser().getId();
		
		String valuess=keyValueRepository.selectValuessByKeyss("issend");
		if(valuess.equals("1")){
			operatorOrderService.sendMessage(userId);
		}
		
		Map<String, String> map = operatorActiveTaskDao.findActiveIdAndLuckNameByTruePriceAndTaskTypeId(provideOrderFormId, taskTypeId);
		
		if(map == null){
			return null;
		}
		
		String result = null;
		String activeId = map.get("id");
		String luckName = map.get("luckName");

		boolean flag = false;//判断是否返回了活动id
		if("大转盘".equals(luckName) && activeId != null && activeId.trim().length() != 0){
			result = operatorLotteryUrlRepository.findUrlByType("ferris_wheel") + activeId;
			flag = true;
		}
		if("砸金蛋".equals(luckName) && activeId!= null && activeId.trim().length() != 0){
			result = operatorLotteryUrlRepository.findUrlByType("egg_frenzy") + activeId;
			flag = true;
		}
		if(flag){
			
			
			//向t_operator_active_chance添加或修改记录.若根据active_id和user_id查找记录，若存在则number字段加一；否则添加记录，number为1
			OperatorActiveChance oac = null;
			try {
				oac = operatorActiveChanceRepository.queryActiveChanceByuserId(userId, activeId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(oac == null){
				oac = new OperatorActiveChance();
				oac.setActiveId(activeId);
				oac.setUserId(userId);
				oac.setNumber(1);
			} else{
				oac.setNumber(oac.getNumber()==null?0:oac.getNumber() + 1);
			}
			operatorActiveChanceRepository.save(oac);
			
			//发送站内信
			String orderNumber = provideOrderForm.getOrderNumber();
			operatorSendMesToCusService.sendPayFor(result+"&userId="+userId, userId, orderNumber);
			
			return result;
		}
		
		return null;
	}

	/**
	 * 
	 * @param userId 用户ID
	 * @param taskTypeId  任务类型ID。根据任务类型查询对应活动ID
	 * @return 抽奖页面的url以及用户剩余抽奖次数
	 */
	@Override
	@Transactional
	public Map<String, String> findActiveURL(String userId, String taskTypeId) {
		Map<String, String> map = new HashMap<String, String>();
		
		//检查检索结果
		List<Object[]> activeIdList = operatorActiveTaskRepository.selectActiveId(taskTypeId);
		if(activeIdList == null || activeIdList.size() == 0){
			map.put("state", "error");
			map.put("msg", "无此任务类型的活动");
			return map;
		}
		if(activeIdList.get(0)[0] == null || ((String)activeIdList.get(0)[0]).length() == 0){
			map.put("state", "error");
			map.put("msg", "此任务类型的活动的id为空");
			return map;
		}
		if(activeIdList.get(0)[1] == null || ((String)activeIdList.get(0)[1]).length() == 0){
			map.put("state", "error");
			map.put("msg", "此任务类型的活动的luckName为空");
			return map;
		}
		String activeId = (String)activeIdList.get(0)[0];
		String luckName = (String)activeIdList.get(0)[1];
		
		//查询并向map放置url
		String url = "";
		if("大转盘".equals(luckName)){
			url = operatorLotteryUrlRepository.findUrlByType("ferris_wheel") + activeId;
		}else if("砸金蛋".equals(luckName)){
			url = operatorLotteryUrlRepository.findUrlByType("egg_frenzy") + activeId;
		}
		if(url.equals("")){
			map.put("state", "error");
			map.put("msg", "此活动的抽奖模式既不是大转盘也不是砸金蛋");
			return map;
		}
		map.put("url", url);
		
		//查询并向map放置chance
		String chance = "0";
		OperatorActiveChance oac = null;
		try {
			oac = operatorActiveChanceRepository.queryActiveChanceByuserId(userId, activeId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(oac == null){
			map.put("state", "error");
			map.put("msg", "查无此人在该活动下的抽奖机会");
			return map;
		}
		map.put("chance", String.valueOf(oac.getNumber()==null?0:oac.getNumber()) );
		
		map.put("state", "success");
		map.put("msg", "查询成功");
		return map;
	}
	
	/**
	 * 被邀请人注册成功后，增加邀请人和被邀请人的抽奖次数
	 * @param inviterId 邀请人的用户ID。可为空
	 * @param inviteeId 被邀请人的用户ID。不可为空
	 * @param taskTypeId 任务类型ID。根据任务类型查询对应活动ID
	 * @return (state, error/success) (msg, *)
	 */
	@Override
	@Transactional
	public Map<String, String> modifyActiveChance(String inviterId, String inviteeId, String taskTypeId) {
		Map<String, String> map = new HashMap<>();
		
		//根据任务类型ID，查询对应活动ID
		List<Object[]> activeIdList = operatorActiveTaskRepository.selectActiveId(taskTypeId);
		if(activeIdList == null || activeIdList.size() == 0){
			map.put("state", "error");
			map.put("msg", "无此任务类型的活动");
			return map;
		}
		if(activeIdList.get(0)[0] == null || ((String)activeIdList.get(0)[0]).length() == 0){
			map.put("state", "error");
			map.put("msg", "此任务类型的活动的id为空");
			return map;
		}
		String activeId = (String)activeIdList.get(0)[0];
		
		//若活动状态不为"已开始"状态，则不增加抽奖次数；若活动不生效，则不增加抽奖次数
		OperatorEventDetails oed = operatorEventDetailsRepository.findOne(activeId);
		if(oed == null){
			map.put("state", "error");
			map.put("msg", "根据活动ID查无此活动");
			return map;
		}
		if(oed.getState() != 2){
			map.put("state", "error");
			map.put("msg", "该活动状态不为'已开始'状态");
			return map;
		}
		if(oed.getAvailability() != 1){
			map.put("state", "error");
			map.put("msg", "该活动未生效");
			return map;
		}
		
		
		//增加邀请人的抽奖次数
		if(inviterId != null && inviterId.length() != 0){
			OperatorActiveChance oac = null;
			try {
				oac = operatorActiveChanceRepository.queryActiveChanceByuserId(inviterId, activeId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(oac == null){
				oac = new OperatorActiveChance();
				oac.setActiveId(activeId);
				oac.setUserId(inviterId);
				oac.setNumber(1);
			} else{
				oac.setNumber(oac.getNumber()==null?0:oac.getNumber() + 1);
			}
			operatorActiveChanceRepository.save(oac);
		}
		
		
		//增加被邀请人的抽奖次数
		OperatorActiveChance oac1 = null;
		try {
			oac1 = operatorActiveChanceRepository.queryActiveChanceByuserId(inviteeId, activeId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(oac1 == null){
			oac1 = new OperatorActiveChance();
			oac1.setActiveId(activeId);
			oac1.setUserId(inviteeId);
			oac1.setNumber(1);
		} else{
			oac1.setNumber(oac1.getNumber()==null?0:oac1.getNumber() + 1);
		}
		operatorActiveChanceRepository.save(oac1);
		
		map.put("state", "success");
		map.put("msg", "修改成功");
		return map;
	}
	
	/**
	 * 减少该用户在该活动下的一次抽奖次数
	 * @param userId 用户ID
	 * @param activeId 活动ID
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, String> minusActiveChance(String userId, String activeId) {
		Map<String, String> map = new HashMap<>();
		
		int result = operatorActiveChanceRepository.updateActiveChance(userId, activeId);
		if(result == 1){
			map.put("state", "success");
			map.put("msg", "修改成功");
			try {
				OperatorActiveChance oac = operatorActiveChanceRepository.queryActiveChanceByuserId(userId, activeId);
				if(oac != null){
					map.put("chance", (oac.getNumber()==null?0:oac.getNumber()) + "");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			map.put("state", "error");
			map.put("msg", "修改失败");
		}
		
		return map;
	}
	
	/**
	 * 查询此任务类型对应的活动的中奖纪录
	 * @param taskTypeId 任务类型ID。根据任务类型ID查询对应活动ID
	 * @return (state, error/success) (msg, *)
	 */
	@Override
	@Transactional
	public Map<String, Object> findLuckdrawRecord(String taskTypeId) {
		Map<String, Object> map = new HashMap<>();
		
		//根据任务类型ID，查询对应活动ID
		List<Object[]> activeIdList = operatorActiveTaskRepository.selectActiveId(taskTypeId);
		if(activeIdList == null || activeIdList.size() == 0){
			map.put("state", "error");
			map.put("msg", "无此任务类型的活动");
			return map;
		}
		if(activeIdList.get(0)[0] == null || ((String)activeIdList.get(0)[0]).length() == 0){
			map.put("state", "error");
			map.put("msg", "此任务类型的活动的id为空");
			return map;
		}
		String activeId = (String)activeIdList.get(0)[0];

		//查询最近30条中奖纪录
		OperatorLuckdrawRecord eTemp = new OperatorLuckdrawRecord();
		eTemp.setActivityId(activeId);
		ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("activityId", GenericPropertyMatchers.exact());
		Example<OperatorLuckdrawRecord> example = Example.of(eTemp, matcher);
		Sort sort = new Sort(Direction.DESC, "recordTime");
		PageRequest pageRequest = new PageRequest(0, 30, sort);
		Page<OperatorLuckdrawRecord> page = operatorLuckdrawRecordRepository.findAll(example, pageRequest);
		
		//根据30个userid查询30个username
		List<OperatorLuckdrawRecord> pageContent = page.getContent();
		String[] userids = new String[pageContent.size()];
		int i = 0;
		for(OperatorLuckdrawRecord temp : pageContent){
			String uid = temp.getUserId();
			if(uid != null && uid.length() != 0){
				userids[i++] = uid;
			}
		}
		Map<String, String> usernameMap = operatorActiveTaskDao.findUsernameByUserid(userids);
		
		//构建返回数据集
		List<OperatorLuckdrawRecordVO> resultList = new ArrayList<>();
		Calendar now = Calendar.getInstance();
		for(OperatorLuckdrawRecord olrTemp : pageContent){
			OperatorLuckdrawRecordVO olrvoTemp = new OperatorLuckdrawRecordVO();
			
			olrvoTemp.setRecordTime(olrTemp.getRecordTime());
			olrvoTemp.setLuckdrawType(olrTemp.getLuckdrawType());
			olrvoTemp.setUserName(usernameMap.get(olrTemp.getUserId()));
			
			//处理时间格式。最终格式为"3分钟前"
			Calendar old = Calendar.getInstance();
			old.setTime(olrvoTemp.getRecordTime());
			long minute = (now.getTimeInMillis() - old.getTimeInMillis()) / (60 * 1000);
			olrvoTemp.setRecordTimeForShow( String.valueOf( (minute==0?1:minute) + "分钟"));
			
			resultList.add(olrvoTemp);
		}
		
		map.put("state", "success");
		map.put("msg", "查询成功");
		map.put("content", resultList);
		return map;
	}
	
	/**
	 * 查询此任务类型对应的活动ID
	 * @param taskTypeId
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, String> findActiveId(String taskTypeId) {
		Map<String, String> map = new HashMap<>();
		
		//根据任务类型ID，查询对应活动ID
		List<Object[]> activeIdList = operatorActiveTaskRepository.selectActiveId(taskTypeId);
		if(activeIdList == null || activeIdList.size() == 0){
			map.put("state", "error");
			map.put("msg", "无此任务类型的活动");
			return map;
		}
		if(activeIdList.get(0)[0] == null || ((String)activeIdList.get(0)[0]).length() == 0){
			map.put("state", "error");
			map.put("msg", "此任务类型的活动的id为空");
			return map;
		}
		String activeId = (String)activeIdList.get(0)[0];
		
		map.put("state", "success");
		map.put("msg", "查询成功");
		map.put("content", activeId);
		return map;
	}
	
	/**
	 * 查询该用户的所有地址信息
	 * @param userId 用户ID
	 * @return (state, error/success) (msg, 提示信息) (content, list)
	 */
	@Override
	@Transactional
	public Map<String, Object> findPersonalAddress(String userId) {
		Map<String, Object> map = new HashMap<>();
		
		List<Object[]> pList = personalAddressRepository.findByUserId(userId);
		List<PersonalAddress> resultList = new ArrayList<>();
		for(Object[] objs:pList){
			PersonalAddress p = new PersonalAddress();//u.id, u.name, u.address, u.telephone, u.isdefault
			p.setId((String)(objs[0]==null?"":objs[0]) );
			p.setName((String)(objs[1]==null?"":objs[1]) );
			p.setAddress((String)(objs[2]==null?"":objs[2]) );
			p.setTelephone((String)(objs[3]==null?"":objs[3]) );
			p.setIsdefault((String)(objs[4]==null?"":objs[4]) );
			p.setUser(null);
			resultList.add(p);
		}
		
		map.put("state", "success");
		map.put("msg", "查询成功");
		map.put("content", resultList);
		
		return map;
	}

	/**
	 * 根据活动 用户 id查询奖项信息 及剩余次数   完全copy的宏伟代码
	 * @param: id 活动ID
	 * @param: userId 用户ID
	 * @return
	 */
	@Transactional
	@Override
	public OperatorLuckdraw getLuckdrawListByActivityId(String id, String userId) {
		OperatorLuckdraw operatorLuckdraw = new OperatorLuckdraw();
		OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository.findOne(id);
		if(userId==null || userId.equals("")==true){
			String sql = "SELECT DISTINCT(ol.prize_name), ol.pic_url, oed.event_pic_url,oed.event_infor FROM t_operator_luckdraw ol,t_operator_event_details oed WHERE ol.activity_id = oed.id AND ol.activity_id =:id ORDER BY ol.weight DESC";
			Query query = manager.createNativeQuery(sql, OperatorLuckdrawAndDetails.class);
			@SuppressWarnings("unchecked")
			List<OperatorLuckdrawAndDetails> enlist = (List<OperatorLuckdrawAndDetails>) query.setParameter("id", id)
					.getResultList();
			operatorLuckdraw.setDrawList(enlist);
			operatorLuckdraw.setSurplusNum(operatorEventDetails.getLuckDrawNum());
			return operatorLuckdraw;
		}
		if(userId!=null || userId.equals("")!=true){
			Integer num = operatorEventDetails.getLuckDrawNum();
			int count = 0;
			if (operatorEventDetails.getLuckDrawType() == 0) {
				try {
					count = operatorLuckdrawRecordRepository.queryCountByUseridAndActivityId(userId, id);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (operatorEventDetails.getLuckDrawType() == 1) {
				Date date = new Date();
				@SuppressWarnings("unused")
				Date timeOne = new Date();
				@SuppressWarnings("unused")
				Date timeTwo = new Date();
				long time = date.getTime();
				time = time + 86400000;
				java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
				try {
					timeOne = dateFormat.parse(dateFormat.format(date));
					timeTwo = dateFormat.parse(dateFormat.format(new Date(time)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				try {
					count = operatorLuckdrawRecordRepository.queryCountByUseridAndActivityIdAndTime(userId, id, timeOne,
							timeTwo);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Integer surplusNum = num - count;
			if(operatorEventDetails.getLuckDrawType() == 2){//下单抽奖
				OperatorActiveChance operatorActiveChance = null;
				try {
					operatorActiveChance = operatorActiveChanceRepository.queryActiveChanceByuserId(userId,id);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(operatorActiveChance != null){
					surplusNum = operatorActiveChance.getNumber();
				}
				if(operatorActiveChance ==null){
					surplusNum=0;
				}
			}
			String sql = "SELECT DISTINCT(ol.prize_name), ol.pic_url, oed.event_pic_url,oed.event_infor FROM t_operator_luckdraw ol,t_operator_event_details oed WHERE ol.activity_id = oed.id AND ol.activity_id =:id ORDER BY ol.weight DESC";
			Query query = manager.createNativeQuery(sql, OperatorLuckdrawAndDetails.class);
			@SuppressWarnings("unchecked")
			List<OperatorLuckdrawAndDetails> enlist = (List<OperatorLuckdrawAndDetails>) query.setParameter("id", id)
					.getResultList();
			List<LuckdrawRecordAndCoupons> recordList = luckdrawRecordAndCouponsdao.queryAllLuckRecordAndCouponsDao(userId,
					id);
			operatorLuckdraw.setSurplusNum(surplusNum);
			operatorLuckdraw.setDrawList(enlist);
			operatorLuckdraw.setRecordCouponsList(recordList);
			return operatorLuckdraw;
		}
		return null;
		
	}
}
